<template>
  <a-modal
    :visible="visible"
    title="收支流水退款配置"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="submitLoading"
    :width="500"
    :destroyOnClose="true"
  >
    <a-spin :spinning="spinning">
      <a-alert message="选定费用类型后，在操作退租的预存费用和收支流水退款时将生成此费用类型的退款账单，修改此费用类型不影响已经操作生成的退款账单" type="warning" />
      <a-form layout="vertical" class="mt-10">
        <a-row :gutter="12">
          <a-col :span="24">
            <a-form-item label="费用类型" v-bind="validateInfos.cost_type">
              <a-cascader
                v-model:value="modelRef.cost_type"
                :options="costTypeList"
                :load-data="getCostTypeSub"
                placeholder="请选择费用类型"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  reactive,
  watch,
  toRefs,
  computed,
  toRaw,
  createVNode,
} from "vue";
import {Form, message} from "ant-design-vue";
import request from "@/common/utils/request";
const useForm = Form.useForm;
export default defineComponent({
  name: "RefundConfigModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, {emit}) {
    const state = reactive({
      costTypeList: [],
      submitLoading: false,
      id: 0,
      spinning: false,
    });

    const modelRef = reactive({
      cost_type: undefined,
    });
    const rulesRef = reactive({
      cost_type: [{required: true, message: "必填项"}],
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const handleOk = () => {
      validate().then(() => {
        state.submitLoading = true;
        let params = {...modelRef};
        if (state.id) {
          params.id = state.id;
        }
        if (params.cost_type && params.cost_type.length == 2) {
          params.cost_type = params.cost_type[1];
        }
        request
          .post("/org", "/billTransfer/addRefundConfig", params)
          .then((res) => {
            message.success(res?.msg || '保存成功');
            state.submitLoading = false;
            emit('handleSettingSuccess');
          });
      })
    };

    const handleCancel = () => {
      emit('handleCancel')
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
        .get("/org", "/bill/costList", {
          page: 1,
          limit: 9999,
          category_id: targetOption.value,
          status: 1,
        })
        .then((res) => {
          if (res.list) {
            targetOption.loading = false;
            targetOption.children = res.list.map((item) => ({
              label: item.name,
              value: item.cost_type,
              isLeaf: true,
            }));
            state.costTypeList = [...state.costTypeList];
          }
        });
    };

    const getCostList = () => {
      return new Promise((resolve) => {
        request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
          state.costTypeList = (res.list || []).map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
          resolve();
        });
      })
    };

    const getDetail = () => {
      state.spinning = true;
      request.get("/org", "/billTransfer/getRefundConfig").then((res) => {
        state.id = res?.list?.id;
        getCostList().then(() => {
          let category_id = res?.list?.cost_type_parentid;
          let cost_type = res?.list?.cost_type;
          if (category_id && cost_type) {
            state.costTypeList.forEach((item) => {
              if (item.value == category_id) {
                request
                  .get("/org", "/bill/costList", {
                    page: 1,
                    limit: 9999,
                    category_id: category_id,
                    status: 1,
                  }).then((res) => {
                  if (res.list) {
                    item.children = res.list.map((item) => ({
                      label: item.name,
                      value: item.cost_type,
                      isLeaf: true,
                    }));
                    modelRef.cost_type = [
                      category_id,
                      cost_type,
                    ];
                  }
                })
              }
            })
          }
          state.spinning = false;
        });
      });
    };

    const init = () => {
      getDetail();
    };

    const reset = () => {
      resetFields();
      state.submitLoading = false;
      state.id = 0;
      state.spinning = false;
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );

    return {
      ...toRefs(state),
      modelRef,
      validateInfos,
      handleOk,
      handleCancel,
      getCostTypeSub,
    };
  },
});
</script>
<style lang="less" scoped>
:deep(.ant-alert-content) {
  font-size: 12px;
}

:deep(.ant-alert.ant-alert-no-icon) {
  padding: 6px 10px;
}
</style>
